package com.datastructure.test.deletereciprocallistnode;

import java.util.List;

public class DeleteReciprocalListNode {
    public static void main(String[] args) {

    }

    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        if(head==null){
            return null;
        }
        if(n==0){
            return head;
        }
        int lengthOfListNode = getLengthOfListNode(head);
        if(lengthOfListNode==n&&lengthOfListNode==1){
            return null;
        }
        if(lengthOfListNode==n&&lengthOfListNode>1){
            return head.next;
        }
        ListNode temp = head;
        for (int i = 0; i < lengthOfListNode - n - 1; i++) {
            temp = temp.next;
        }
        if(n==1){
            temp.next = null;
        } else {
            temp.next = temp.next.next;
        }
        return head;
    }

    public int getLengthOfListNode(ListNode head){
        int result = 0;
        while (head!=null){
            result++;
            head = head.next;
        }
        return result;
    }
}
class ListNode {
 int val;
 ListNode next = null;
}
